import { DB } from './db/db'
import crypto from 'crypto'
import CryptoJs from 'crypto-js'


async function isUserExist(uname: string) {
    return await DB
        .select('uname')
        .from('userInfo')
        .where('uname', uname)
        .queryValue();
}

export async function userRegister(params: { username: string, password: string, [key: string]: any }) {
    const { username, password } = params

    const isExist = await isUserExist(username)
    if (isExist) {
        return { success: false, msg: 'user exist' }
    }

    // 生成10字符长salt，并和psw一起生成密码校验值（sha256）
    const salt = crypto.randomBytes(5).toString('hex')
    const pswHash = CryptoJs.SHA256(password + salt).toString()

    const uid = crypto.randomBytes(5).toString('hex')
    const result = await DB
        .insert('userInfo')
        .column('uid', uid)
        .column('salt', salt)
        .column('uname', username)
        .column('pswHash', pswHash)
        .execute();
    if (result.insertId.toString()) {
        return { success: true }
    } else {
        return { success: false, msg: "db insert failed" }
    }

}

export async function userLogin(params: { username: string, password: string }) {
    const { username, password } = params
    const userInfo = await DB
        .select('*')
        .from('userInfo')
        .where('uname', username)
        .queryRow()
    if(!userInfo){
        return {success:false,msg:'no user!'}
    }
    
    const { salt, pswHash, uid, uname } = userInfo;
    const _pswHash = CryptoJs.SHA256(password + salt).toString()
    if (!(_pswHash === pswHash)) {
        return { success: false, msg: 'pass word error' }
    }

    return { success: true, data: { userInfo: { uid, uname } } }
}
